package mh.demo.jdk.lang;

import java.util.concurrent.TimeUnit;

/**
 * 《Java并发编程艺术》书中的本地线程demo
 */
public class ThreadLocalDemo {
    // 第一次 get()方法调用时会进行初始化（如果 set 方法没有调用），每个线程会调用一次
    private static final ThreadLocal<Long> TIME_THREAD_LOCAL = new ThreadLocal<>();

    protected Long initialValue() {
        return System.currentTimeMillis();
    }

    public static void begin() {
        TIME_THREAD_LOCAL.set(System.currentTimeMillis());
    }

    public static long end() {
        return System.currentTimeMillis() - TIME_THREAD_LOCAL.get();
    }

    public static void main(String[] args) throws Exception {
        ThreadLocalDemo.begin();
        TimeUnit.SECONDS.sleep(1);
        System.out.println("Cost: " + ThreadLocalDemo.end() + " mills");
    }
}
